package com.narata.netty;

import java.nio.ByteBuffer;

/**
 * @Author: XJL
 * @Description: 处理半包和闭包问题
 * @Date: Create in 22:58 2021-11-07
 * @Modified By:
 **/
public class ByteBufferExam {
    public static void main(String[] args) {
        ByteBuffer source = ByteBuffer.allocate(32);
        source.put("Hello,world\nI`m zhangsan\n Ho".getBytes());
        split(source);
        source.put("w are you?\n".getBytes());
        split(source);

    }

    private static void split(ByteBuffer source) {
        source.flip();
        for (int i=0;i<source.limit();i++) {
            byte b = source.get(i);
            // 找到一条完整的消息
            if (b == '\n') {
                int leng = i + 1 - source.position();
                // 把这条完整消息存入新的ByteBuffer
                ByteBuffer target = ByteBuffer.allocate(leng);
                // 从source写，向target读
                for (int j=0; j<leng;j++) {
                    target.put(source.get());
                }
            }
        }
        source.compact();
    }
}
